import {
  deleteDepositApi,
  getListApi,
  getPageStaticApi,
  reverseApprovalApi,
  reverseChargeOffDepositApi,
  depositExceltApi,
  downAllDataApi
} from "@/api/financialManagement/receivable/waterVerification";
// import CommonHook from "@/hook/commonHook";
import dayjs from "dayjs";
import { Modal, message } from "ant-design-vue";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
export default function OperationHook(state: {
  searchForm: WaterVerification.SearchForm;
  tableData: Ref<WaterVerification.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<string>;
  pageStat: Ref<Base.GeneraDataType>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, activeKey, pageStat } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  // const { getNoZeroKey } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { createByList, accountIdList, customerNames, customerIdList, proceedsTime, pageNum, pageSize, chargeOffStateList, billNum, companyIdList, orderNums } = searchForm;
    const params: any = {
      accountIdList,
      createByList,
      proceedsStartTime: proceedsTime.length ? dayjs(proceedsTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
      proceedsEndTime: proceedsTime.length ? dayjs(proceedsTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
      pageNum,
      pageSize,
      chargeOffStateList,
      customerIdList,
      billNum,
      companyIdList
    };
    switch (activeKey.value) {
      case "0":
        params.approvalState = undefined;
        params.state = undefined;
        break;
      case "1":
        params.approvalState = 0;
        break;
      case "2":
        params.approvalState = 1;
        params.state = 0;
        break;
      case "3":
        params.approvalState = 1;
        params.state = 1;
    }
    if (customerNames) {
      params.customerNames = customerNames
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }
    if (createByList.length) {
      params.createByList = createByList.map((t: any) => t[t.length - 1]);
    }
    if (accountIdList.length) {
      params.accountIdList = accountIdList.map((t: any) => t[t.length - 1]);
    }
    if (orderNums) {
      params.orderNums = orderNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }

    return params;
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          1: data[1],
          2: data[2],
          3: data[3],
          0: data[0]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["1", "2", "3"]));
      }
    });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  // 批量导入来款
  const batchImportDepsoitHandle = () => {
    dialogOpts.title = `批量导入来款`;
    dialogOpts.width = "850px";
    dialogOpts.type = 1;
    dialogOpts.component = "BatchImportDeposit";
    dialogOpts.visible = true;
  };
  // 查看删除记录
  const showDeleteLogHandle = () => {
    drawerOpts.title = `删除来款记录`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "DeleteLog";
    drawerOpts.visible = true;
  };
  // 审核
  const auditDepositHandle = (row: WaterVerification.ListRows) => {
    drawerOpts.title = `审核来款`;
    drawerOpts.width = "1000px";
    drawerOpts.type = 1;
    drawerOpts.passData = row;
    drawerOpts.component = "AuditDeposit";
    drawerOpts.visible = true;
  };
  // 删除来款
  const deleteDepositHandle = (row: WaterVerification.ListRows) => {
    Modal.confirm({
      title: "是否删除当前来款?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        deleteDepositApi({ id: row.id }).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("删除成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 反审核
  const reverseApprovalHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选流水!");
    return reverseApprovalApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成!");
        searchHandle();
      }
    });
  };
  // 反核销
  const reverseChargeOffHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选流水!");
    return reverseChargeOffDepositApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        searchHandle();
      }
    });
  };
  // 日志
  const showLogHandle = (row: WaterVerification.ListRows) => {
    drawerOpts.title = `流水日志`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "OperationLog";
    drawerOpts.passData = [row];
    drawerOpts.visible = true;
  };
  // 核销账单
  const chargeOffBillHandle = (row: WaterVerification.ListRows) => {
    drawerOpts.title = `核销账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "VerificationBill";
    drawerOpts.passData = [row];
    drawerOpts.visible = true;
  };
  // 批量核销账单
  const batchChargeOffBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选账单!");
    const allCustomerId = Array.from(new Set(selectRows.value.map((t: any) => t.customerId)));
    if (allCustomerId.length > 1) return message.error("只能核销同一客户的账单!");
    drawerOpts.title = `核销账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "VerificationBill";
    drawerOpts.passData = selectRows.value;
    drawerOpts.visible = true;
  };
  //导出
  const downloadDataHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined
    };

    return depositExceltApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };
  //导出全部流水
  const downloaAlldDataHandle = () => {
    return downAllDataApi().then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };

  // 核销备注
  const verificationRemarkHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选账单!");
    dialogOpts.title = `核销备注`;
    dialogOpts.width = "520px";
    dialogOpts.passData = selectRows.value;
    dialogOpts.component = "VerificationRemark";
    dialogOpts.visible = true;
  };

  return {
    searchHandle,
    getData,
    changeTabHandle,
    batchImportDepsoitHandle,
    showDeleteLogHandle,
    auditDepositHandle,
    deleteDepositHandle,
    reverseApprovalHandle,
    reverseChargeOffHandle,
    showLogHandle,
    chargeOffBillHandle,
    batchChargeOffBillHandle,
    downloadDataHandle,
    downloaAlldDataHandle,
    verificationRemarkHandle
  };
}
